package com.baomibing.flow.model;

import com.baomibing.core.exception.ServerRuntimeException;
import com.baomibing.flow.constant.NodeTypeEnum;
import com.baomibing.flow.exception.FlowExceptionEnum;
import com.baomibing.flow.execute.Execution;
import com.baomibing.tool.util.Checker;
import com.google.common.collect.Lists;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * EndNode
 *
 * @author frog 2023/9/18 17:20
 * @version 1.0.0
 **/
@Slf4j
@ToString
public class EndNode extends WorkNode{

    @Override
    public List<TransitionNode> getOutputs() {
        return Lists.newArrayList();
    }

    @Override
    public void execute(Execution execution) {
        log.info("*****process: 正在执行EndNode({}),执行人:{}", this.getName(),  execution.getActor());
        flow.updateWorkNode(null, this);

    }

    @Override
    public void reject(Execution execution) {
        log.info("*****reject: 正在执行EndNode({}),执行人:{}", this.getName(), execution.getActor());
        String actor = execution.getActor();
        if (getInputs().size() == 1) {
            getInputs().get(0).reject(execution);
            return;
        }
        if (Checker.beEmpty(actor)) {
            throw new ServerRuntimeException(FlowExceptionEnum.END_NODE_HAVE_MULTI_TRANSITION_NEED_ACTOR);
        }
        boolean find = false;
       for (TransitionNode line : getInputs()) {
           if (line.getSource() instanceof TaskNode) {
               TaskNode tn = (TaskNode) line.getSource();
               if (tn.getEntrusts().contains(actor)) {
                   find = true;
                   line.reject(execution);
               }
           }
       }
       if (!find) {
           throw new ServerRuntimeException(FlowExceptionEnum.NOT_FOUND_THE_CORRECT_ACTOR_WHEN_REJECTING);
       }
    }

    public EndNode(String name) {
        this.name = name;
        this.nodeType = NodeTypeEnum.End.name();
    }

    //for json deserialize
    public EndNode() {
        this.nodeType = NodeTypeEnum.End.name();
    }
}
